package com.xxl.servlet;

import com.xxl.services.ClassesService;
import com.xxl.services.StudentService;
import com.xxl.services.impl.ClassesServiceImpl;
import com.xxl.services.impl.StudentServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("*.forward")
public class ForwardServlet extends HttpServlet {
    StudentService studentService = new StudentServiceImpl();
    ClassesService classesService = new ClassesServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();
        String reqName = servletPath.split("\\.")[0].split("/")[1];
        String path = "/WEB-INF/"+ reqName +".jsp";
        ServletContext servletContext = req.getServletContext();
        servletContext.setAttribute("path",path);
        req.setCharacterEncoding("UTF-8");
        List list = new ArrayList();
        if ("student".equals(reqName)){
            try {
                studentService.listAddStudent(list);
            } catch (SQLException throwables) {
                System.out.println(throwables);
            }
            req.setAttribute("student", list);
        }else if ("classes".equals(reqName)){
            try {
                classesService.listAddClasses(list);
            } catch (SQLException throwables) {
                System.out.println(throwables);
            }
            req.setAttribute("classes", list);
        }
        req.getRequestDispatcher(path).forward(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
